
var TableDatatablesEditable = function () {

    var handleTable = function () {

        var nEditing = null;
        var nNew = false;

        function getAllMoney(oTable){
        	var dataArray = oTable.DataTable().data().toArray();
        	var sqzje = 0;
        	for(var i = 0, iLen = dataArray.length; i < iLen; i++){
        		if(!isNaN(parseFloat(dataArray[i].mxsl)) && !isNaN(parseFloat(dataArray[i].mxdj))){
        			sqzje += (parseFloat(dataArray[i].mxsl) * parseFloat(dataArray[i].mxdj));
        		}
        	}
        	$('#sqzje').val(sqzje)
        }
        
    	function editRow(oTable, nRow) {
            var jqTds = $('>td', nRow);
            var aData = jqTds;
			var td_num = jqTds.length - 1;
			var i = 0
			while(i < td_num){
				// if(i==0){
				// 	jqTds[i].innerHTML = '<input type="text" disabled="true" class="form-control input-small" value="' + aData[i].innerHTML + '">';
				// }else{
				// 	jqTds[i].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[i].innerHTML + '">';
				// }
                if(i==5){
                    jqTds[i].innerHTML = '<input type="text" id="mxzjeText'+nRow._DT_RowIndex+'" readonly class="form-control input-small" >';
                }else if(i==3){
                    jqTds[i].innerHTML = '<input type="text" id="mxslText'+nRow._DT_RowIndex+'" onblur="getMoney(this.id,\'mxdjText'+nRow._DT_RowIndex+'\',\'mxzjeText'+nRow._DT_RowIndex+'\');" class="form-control input-small" >';
                }else if(i==4){
                    jqTds[i].innerHTML = '<input type="text" id="mxdjText'+nRow._DT_RowIndex+'" onblur="getMoney(\'mxslText'+nRow._DT_RowIndex+'\',this.id,\'mxzjeText'+nRow._DT_RowIndex+'\');" class="form-control input-small" >';
                }else if(i==0){
                    jqTds[i].innerHTML = '<input type="text" id="txmText'+nRow._DT_RowIndex+'" onblur="getZbmc(this.id,this.value,\'zbmcText'+nRow._DT_RowIndex+'\');" class="form-control input-small">';
                }else if(i==1){
                    jqTds[i].innerHTML = '<input type="text" readonly id="zbmcText'+nRow._DT_RowIndex+'" class="form-control input-small" >';
                }else {
                    jqTds[i].innerHTML = '<input type="text" class="form-control input-small" >';
                }
                i++;
			}
            jqTds[i].innerHTML = '<a class="delete" href="">删除</a>';
            getAllMoney(oTable);
        }

        var table = $('#sample_editable_1');

        var oTable = table.dataTable({
            "sDom" : "<'row-fluid'<'pull-left filterInput'>>t<'row-fluid'<'span4'il><'span7'<'pull-right'p>>>",
			 "columns": [
				/*{data: "id", orderable: false, className: "center", title: "id",defaultContent: ""},*/
				{data: "txm", orderable: false, className: "center", title: "条形码",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text" id="txmText'+meta.row+'" onblur="getZbmc(this.id,this.value,\'zbmcText'+meta.row+'\');" class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text" id="txmText'+meta.row+'" onblur="getZbmc(this.id,this.value,\'zbmcText'+meta.row+'\');" class="form-control input-small" >';
							}
						}
	                    return html;
	                }
				},
				{data: "zbmc", orderable: false, className: "center", title: "装备名称",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text" readonly id="zbmcText'+meta.row+'" class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text" readonly id="zbmcText'+meta.row+'" class="form-control input-small">';
							}
							
						}
	                    return html;
	                    }
				},
				{data: "qcmc", orderable: false, className: "center", title: "器材名称",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text" class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text" class="form-control input-small" >';
							}
							
						}
	                    return html;
	                    }
				},
				{data: "mxsl", orderable: false, className: "center numinput account", title: "数量",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text" id="mxslText'+meta.row+'" onblur="getMoney(this.id,\'mxdjText'+meta.row+'\',\'mxzjeText'+meta.row+'\');" class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text" id="mxslText'+meta.row+'" onblur="getMoney(this.id,\'mxdjText'+meta.row+'\',\'mxzjeText'+meta.row+'\');" class="form-control input-small">';
							}
						}
	                    return html;
	                    }
				},
				{data: "mxdj", orderable: false, className: "center numinput price", title: "单价",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text" id="mxdjText'+meta.row+'" onblur="getMoney(\'mxslText'+meta.row+'\',this.id,\'mxzjeText'+meta.row+'\');" class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text" id="mxdjText'+meta.row+'" onblur="getMoney(\'mxslText'+meta.row+'\',this.id,\'mxzjeText'+meta.row+'\');" class="form-control input-small" >';
							}
						}
	                    return html;
	                    }
				},
				{data: "mxzje", orderable: false, className: "center numinput sumprice", title: "总金额",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text" id="mxzjeText'+meta.row+'" readonly class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text" id="mxzjeText'+meta.row+'" readonly class="form-control input-small">';
							}
							
						}
	                    return html;
	                    }
				},
				{data: "bz", orderable: false, className: "center", title: "备注",defaultContent: "",
					mRender: function (data, type, row, meta) {
						var html = "";
						if($('#jfsfbj').val()){
							if(data){
								html += '<input type="text"  class="form-control input-small" value="' + data + '">';
							}else{
								html += '<input type="text"  class="form-control input-small" >';
							}
						}
	                    return html;
	                    }
				},
				{
					data: null,
					orderable: false,
					className: "center opera",
					title: "操作",
					width: "80",
					mRender: function (data, type, row, meta) {
                    var html = '<a class="delete" href="">删除</a>';
                    return html;
                    }
				},{data: "jfsqid", orderable: false,visible:false, className: "center", defaultContent: ""}
			],
			

            // set the initial value
            "pageLength": 5,
            "bServerSide": false,
            sScrollXInner: "150%",
            sScrollX: "100%",
			"sAjaxSource": ctx+'/jfsq/getMxData',
			"fnServerData": function (sSource, aoData, fnCallback) {
			    var jfsqId = $('#jfsqIdValue').val();
				$.ajax({
					headers: {
						Accept: "application/json; charset=utf-8"
					},
					"type" : 'post',
					"url" : sSource,
					"sync" : true,
					"dataType" : "json",
					"data" : {"jfsqId":jfsqId},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			},
			
            "columnDefs": [
                { // set default column settings
                'orderable': true,
                'targets': [0]
            }, {
                "searchable": true,
                "targets": [0]
            }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        var tableWrapper = $("#sample_editable_1_wrapper");

        $('#sample_editable_1_new').click(function (e) {
            e.preventDefault();

            var aiNew = oTable.fnAddData(['', '', '', '', '', '', '', '', '']);
            var nRow = oTable.fnGetNodes(aiNew[0]);
            editRow(oTable, nRow);
            nEditing = nRow;
            nNew = true;
        });
        var editval = []
        var cancelItem = false;

        table.on('click', '.delete', function (e) {
            cancelItem = false;
            var $a = this;
            e.preventDefault();
            if (confirm("确认删除本行数据?") == false) {
                return;
            }
            var nRow = $(this).parents('tr')[0];
            oTable.fnDeleteRow(nRow);
            getAllMoney(oTable);
            
            // alert("Deleted! Do not forget to do some ajax to sync with backend :)");
        });

    }

    return {

        //main function to initiate the module
        init: function () {
            handleTable();
        }

    };

}();


function getZbmc(txmid,txm,id){
	var ctx = $('#ctxValue').val();
	 $.ajax({
         "type" : 'post',
         "url" : ctx+'/jfsq/getZbmcData',
         "sync" : false,
         "dataType" : "json",
         "data" : {'txm':txm},
         "success" : function(data){
        	 if(data.data){
        		 document.getElementById(txmid).style.border = '';
         		 $('#'+id).val(data.data);
        	 }else{
        		 document.getElementById(txmid).style.border = '1px solid #FF0000';
        		 $('#'+id).val("");
        	 }
         },
         error : function(xhr, textStatus, exception) {
         }
	 });
}

function getMoney(mxslid,mxdjid,mxzjeid){
	var mxsl = $('#'+mxslid).val();
	var mxdj = $('#'+mxdjid).val();
	if(mxsl && mxsl){
		if(!isNaN(parseFloat(mxsl)) && !isNaN(parseFloat(mxdj))){
			$('#'+mxzjeid).val(parseFloat(mxsl) * parseFloat(mxdj));
		}else{
			$('#'+mxzjeid).val("");
		}
	}else{
		$('#'+mxzjeid).val("");
	}
	
}

jQuery(document).ready(function() {
	
    var ctx = $('#ctxValue').val();
    TableDatatablesEditable.init();
    $('#saveJfsq').on('click', function (e) {
        var end = null;
        /*var tableData = $('#sample_editable_1').dataTable();
        var ntrs = tableData.fnGetNodes();
        for(var i = 0;i < ntrs.length;i++){
        	var nRow = null; 
        	nRow = tableData.fnGetNodes(tableData.fnGetData(ntrs[i]));
        	var jqInputs = $('input', nRow);
			var td_num = jqInputs.length;
			var j = 0
			while(j < td_num){
				tableData.fnUpdate(jqInputs[j].value, nRow, j, false);
				j++;
			}
			//tableData.fnUpdate('<a class="delete" href="">删除</a>', nRow, j, false);

			tableData.fnDraw();
        }*/
        
        
        var rows = $("#sample_editable_1 tr");
		$.each(rows, function(index, row) {
			if (index > 0) {
				var jqInputs = $('input', row);
				var td_num = jqInputs.length;
				var j = 0
				if(td_num > 0){
					if(!jqInputs[1].value && !jqInputs[2].value){
						end = "必须有装备名称或者器材名称！";
		    			return false;
					}
					if(!jqInputs[3].value || !jqInputs[4].value){
						end = "数量或单价没有填写完整！";
		    			return false;
					}
				}
				while(j < td_num){
					$('#sample_editable_1').dataTable().fnUpdate(jqInputs[j].value, row, j, false);
					j++;
				}
				//tableData.fnUpdate('<a class="delete" href="">删除</a>', nRow, j, false);

				$('#sample_editable_1').dataTable().fnDraw();
			}
		});
        
        if(!end){
        	var sqzje = 0;
            var jfsqmxList = $('#sample_editable_1').DataTable().data().toArray();
        	for(var i = 0, iLen = jfsqmxList.length; i < iLen; i++){
        		if(!isNaN(parseFloat(jfsqmxList[i].mxsl)) && !isNaN(parseFloat(jfsqmxList[i].mxdj))){
        			sqzje += (parseFloat(jfsqmxList[i].mxsl) * parseFloat(jfsqmxList[i].mxdj));
        		}
        	}
        	$('#sqzje').val(sqzje)
            var jfsq = $('#jfsqForm').serializeObject();
            var array = new Array(jfsqmxList.length)
            for(var i = 0, iLen = jfsqmxList.length; i < iLen; i++){
                var jfsqmx = new Object();
                jfsqmx.id = jfsqmxList[i].id;
                jfsqmx.jfsqid = jfsqmxList[i].jfsqid;
                jfsqmx.txm = jfsqmxList[i].txm;
                jfsqmx.qcmc = jfsqmxList[i].qcmc;
                jfsqmx.zbmc = jfsqmxList[i].zbmc;
                jfsqmx.mxsl = jfsqmxList[i].mxsl;
                jfsqmx.mxdj = jfsqmxList[i].mxdj;
                jfsqmx.mxzje = jfsqmxList[i].mxzje;
                jfsqmx.bz = jfsqmxList[i].bz;
                array[i] = jfsqmx;
            }

            jfsq.jfsqmxList = array;
            $.ajax({
                "type" : 'post',
                "url" : ctx+'/jfsq/jfsq-save',
                "sync" : true,
                "contentType":"application/json;charset=utf-8",
                "data" : JSON.stringify(jfsq),
                "success" : function(resp) {
                    var obj = JSON.parse(resp);
                    if(obj){
                        if(obj.errmsg){
                            notyError(obj.errmsg);
                        }else if(obj.msg){
                            notySuccess(obj.msg);
                            window.location.href = ctx+'/jfsq/jfsq-list';
                        }
                    }
                }
            });
        }else{
        	notyError(end);
        }
    });
    
    
    
    $('#commitJfsq').on('click', function (e) {
    	var end = null;
    	var rows = $("#sample_editable_1 tr");
 		$.each(rows, function(index, row) {
 			if (index > 0) {
 				var jqInputs = $('input', row);
 				var td_num = jqInputs.length;
 				var j = 0;
				if(td_num > 0){
					if(!jqInputs[1].value && !jqInputs[2].value){
						end = "必须有装备名称或者器材名称！";
		    			return false;
					}
					if(!jqInputs[3].value || !jqInputs[4].value){
						end = "数量或单价没有填写完整！";
		    			return false;
					}
				}
 				while(j < td_num){
 					$('#sample_editable_1').dataTable().fnUpdate(jqInputs[j].value, row, j, false);
 					j++;
 				}
 				//tableData.fnUpdate('<a class="delete" href="">删除</a>', nRow, j, false);

 				$('#sample_editable_1').dataTable().fnDraw();
 			}
 		});
 		if(!end){
	 		var sqzje = 0;
	 		var jfsqmxList = $('#sample_editable_1').DataTable().data().toArray();
	    	for(var i = 0, iLen = jfsqmxList.length; i < iLen; i++){
	    		if(!isNaN(parseFloat(jfsqmxList[i].mxsl)) && !isNaN(parseFloat(jfsqmxList[i].mxdj))){
	    			sqzje += (parseFloat(jfsqmxList[i].mxsl) * parseFloat(jfsqmxList[i].mxdj));
	    		}
	    	}
	    	$('#sqzje').val(sqzje)
			var jfsq = $('#jfsqForm').serializeObject();
			var array = new Array(jfsqmxList.length)
			for(var i = 0, iLen = jfsqmxList.length; i < iLen; i++){
				var jfsqmx = new Object();
				jfsqmx.id = jfsqmxList[i].id;
				jfsqmx.jfsqid = jfsqmxList[i].jfsqid;
				jfsqmx.txm = jfsqmxList[i].txm;
				jfsqmx.qcmc = jfsqmxList[i].qcmc;
				jfsqmx.zbmc = jfsqmxList[i].zbmc;
				jfsqmx.mxsl = jfsqmxList[i].mxsl;
				jfsqmx.mxdj = jfsqmxList[i].mxdj;
				jfsqmx.mxzje = jfsqmxList[i].mxzje;
				jfsqmx.bz = jfsqmxList[i].bz;
				array[i] = jfsqmx;
			}
			
			jfsq.jfsqmxList = array;
			 $.ajax({
	             "type" : 'post',
	             "url" : ctx+'/jfsq/jfsq-commit',
	             "sync" : true,
	             "contentType":"application/json;charset=utf-8",
	             "data" : JSON.stringify(jfsq),
	             "success" : function(resp) {
	            	 var obj = JSON.parse(resp);
	            	 if(obj){
	            		 if(obj.errmsg){
	            			 notyError(obj.errmsg);
	            		 }else if(obj.msg){
	            			 notySuccess(obj.msg);
	            			 window.location.href = ctx+'/jfsq/jfsq-list';
	            		 }
	            	 }
	             }
			 });
 		}else{
 			notyError(end);
 		}
    });
    
});